<template>
    <div class="main">
        <div class="header">
            <h2>品牌管理</h2>
        </div>
<!--        搜索表单  -->
        <div class="search-container">
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-input 
                        v-model="bd.name" 
                        placeholder="请输入品牌名称" 
                        clearable
                        prefix-icon="Search"
                        @keyup.enter="search"
                    >
                    </el-input>
                </el-col>
                <el-col :span="16">
                    <el-button type="primary" @click="search">查询</el-button>
                    <el-button type="success" :icon="Plus" @click="add">添加品牌</el-button>
                    <el-button type="danger" :icon="Delete" @click="deleteRows">批量删除</el-button>
                </el-col>
            </el-row>
        </div>
<!--       表格展示区域 -->
        <div class="data-container">
            <el-table 
                :data="tableData" 
                border 
                style="width: 100%"
                :header-cell-style="{ textAlign: 'center', backgroundColor: '#f5f7fa' }"
                :cell-style="{ textAlign: 'center' }" 
                ref="tableRef"
            >
                <el-table-column type="selection" width="55" />
                <el-table-column prop="id" label="编号" width="80" />
                <el-table-column prop="name" label="品牌名" width="120" />
                <el-table-column prop="logo" label="品牌Logo" width="150">
                  <template #default="scope">
                    <div class="logo-container">
                      <img 
                        v-if="scope.row.logo" 
                        :src="scope.row.logo" 
                        class="logo-circle"
                        @click="previewImageFn(scope.row.logo)"
                      />
                      <span v-else class="logo-placeholder">暂无图片</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="company" label="公司名称" width="150" />
                <el-table-column prop="site" label="公司官网" width="180">
                  <template #default="scope">
                    <a 
                      v-if="scope.row.site" 
                      :href="scope.row.site" 
                      target="_blank" 
                      class="site-link"
                    >
                      {{ scope.row.site }}
                    </a>
                    <span v-else>暂无官网</span>
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="品牌描述" min-width="200">
                    <template #default="scope">
                        <div class="description-cell" @click="showFullDescription(scope.row.description)">
                            {{ truncateText(scope.row.description, 50) }}
                        </div>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作" width="180">
                    <template #default="scope">
                        <el-button type="primary" :icon="Edit" @click="editRow(scope.row)" size="small">
                            编辑
                        </el-button>
                        <el-button type="danger" :icon="Delete" @click="deleteRow(scope.row)" size="small">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        
        <!-- 分页组件 -->
        <div class="pagination-container">
            <el-pagination
                v-model:current-page="pagination.pageNo"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="pagination.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
            />
        </div>
        
        <el-dialog 
            v-model="show" 
            :title="title" 
            width="600px" 
            :before-close="handleDialogClose"
            class="brand-dialog"
        >
            <el-form :model="brand" ref="sfRef" label-position="right" label-width="100px">
                <el-form-item label="品牌名称:" prop="name">
                    <el-input placeholder="请输入品牌名称" v-model="brand.name" />
                </el-form-item>
                <el-form-item label="品牌Logo:" prop="logo">
                  <el-upload 
                    class="avatar-uploader"
                    :auto-upload="true"
                    :show-file-list="false" 
                    action="/api/shop-upload-api/upload"
                    name="file"
                    :on-success="uploadSuccess"
                    :before-upload="beforeUpload"
                  >
                    <img v-if="brand.logo" :src="brand.logo" class="logo-circle-preview" />
                    <div v-else class="upload-placeholder">
                      <el-icon class="logo-uploader-icon"><Plus /></el-icon>
                      <div class="upload-text">上传图片</div>
                    </div>
                  </el-upload>
                </el-form-item>
                <el-form-item label="公司名称:" prop="company">
                    <el-input placeholder="请输入公司名称" v-model="brand.company" />
                </el-form-item>
                <el-form-item label="公司网站:" prop="site">
                    <el-input placeholder="请输入公司网站" v-model="brand.site" />
                </el-form-item>
                <el-form-item label="品牌描述:" prop="description">
                    <el-input 
                        type="textarea" 
                        placeholder="请输入品牌描述" 
                        v-model="brand.description" 
                        :rows="4"
                    />
                </el-form-item>
            </el-form>
            
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="show = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确认</el-button>
                </div>
            </template>
        </el-dialog>
        
        <!-- 品牌描述详情弹窗 -->
        <el-dialog 
            v-model="showDescriptionDialog" 
            title="品牌描述详情" 
            width="500px"
        >
            <div class="description-content">
                {{ currentDescription }}
            </div>
            <template #footer>
                <el-button type="primary" @click="showDescriptionDialog = false">确定</el-button>
            </template>
        </el-dialog>
        
        <!-- 图片预览弹窗 -->
        <el-dialog v-model="previewVisible" class="preview-dialog">
            <img width="100%" :src="previewImage" alt="预览图片" />
        </el-dialog>
    </div>
</template>

<script setup>
import { Plus, Edit, Search, Delete } from '@element-plus/icons-vue'
import { ref, onMounted, toRaw, nextTick } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { findAll, deleteById, save, update as updateBrand, deleteAll } from '@/api/BrandApi'

onMounted(() => {
    search()
})

const tableData = ref([])
// 添加分页相关数据
const pagination = ref({
    pageNo: 1,
    pageSize: 10,
    total: 0
})

// 品牌描述相关
const showDescriptionDialog = ref(false)
const currentDescription = ref('')

// 表单相关
const show = ref(false)
const brand = ref({
    name: "",
    logo: "",
    description: "",
    site: "",
    company: "",
})

const title = ref("新增品牌")

// 文件上传相关
const fileList = ref([])
const previewVisible = ref(false)
const previewImage = ref('')

// 上传前检查
function beforeUpload(file) {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
    const isLt2M = file.size / 1024 / 1024 < 2
        
    if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
    }
    return isJPG && isLt2M
}
    
// 上传成功处理
const uploadSuccess = (result) => {
  brand.value.logo = result.data;
  // console.log(result.data);
}
    
// 预览图片
function handlePictureCardPreview(file) {
    previewImage.value = file.url
    previewVisible.value = true
}

// 添加预览图片函数
function previewImageFn(url) {
    previewImage.value = url
    previewVisible.value = true
}

// 搜索条件
const bd = ref({
    name: "",
})

// 表格引用
let tableRef

async function search() {
    let resp = await findAll(pagination.value.pageNo, pagination.value.pageSize, bd.value)
    tableData.value = resp.records
    // 更新分页总数量
    pagination.value.total = resp.total
    tableData.value = tableData.value.map(item => {
        // 将 status 字段从 0/1 转换为 false/true
        return {
            ...item,
            status: item.status === 1,
        }
    })
}

function deleteRow(row) {
    let id = row.id
    deleteBrand(id)
}

// 删除函数
function deleteBrand(id) {
    ElMessageBox.confirm("是否确认删除该品牌?", "警告", {
        type: "warning",
    })
        .then(async () => {
            let resp = await deleteById(id)
            if (resp.code == 200) {
                ElMessage({
                    message: resp.msg,
                    type: "success",
                })
                search()
            } else {
                ElMessage({
                    message: resp.msg,
                    type: "error",
                })
            }
        })
        .catch(() => { })
}

function deleteRows() {
    let rows = tableRef.getSelectionRows()
    let ids = []
    for (let row of rows) {
        ids.push(toRaw(row).id)
    }
    deleteAllRows(ids)
}

async function deleteAllRows(ids) {
    if (ids.length == 0) {
        ElMessage({
            message: "请选择想要删除的行",
            type: "warning",
        })
    } else {
        ElMessageBox.confirm("是否确认删除所选品牌?", "警告", {
            type: "warning",
        })
            .then(async () => {
                // 向后台发送ajax请求
                let resp = await deleteAll(ids)
                if (resp.code == 200) {
                    ElMessage({
                        message: resp.msg,
                        type: "success",
                    })
                    search()
                } else {
                    ElMessage({
                        message: resp.msg,
                        type: "warning",
                    })
                }
            })
            .catch(() => { })
    }
}

async function add() {
    show.value = true
    title.value = "新增品牌"
    // 重置表单数据
    brand.value = {
        name: "",
        logo: "",
        description: "",
        site: "",
        company: "",
    }
}

function submitForm() {
    let brm = toRaw(brand.value)

    if (brm.id) {
        update(brm)
    } else {
        addBrand(brm)
    }
}

async function addBrand(brm) {
    let resp = await save(brm)
    if (resp.code == 200) {
        ElMessage({
            message: "添加成功",
            type: "success",
        })
        search()
        show.value = false
    } else {
        ElMessage({
            message: resp.msg || "添加失败",
            type: "error",
        })
    }
}

function editRow(row) {
    row = Object.assign({}, row)
    show.value = true
    title.value = "编辑品牌"
    nextTick(() => {
        brand.value = row
    })
}

async function update(brm) {
    let resp = await updateBrand(brm)
    if (resp.code == 200) {
        ElMessage({
            message: "修改成功",
            type: 'success',
        })
        search()
        show.value = false
    } else {
        ElMessage({
            message: resp.msg || "修改失败",
            type: 'error',
        })
    }
}

// 处理分页大小改变
function handleSizeChange(val) {
    pagination.value.pageSize = val
    search()
}

// 处理当前页改变
function handleCurrentChange(val) {
    pagination.value.pageNo = val
    search()
}

// 处理对话框关闭
function handleDialogClose(done) {
    ElMessageBox.confirm('确认关闭？')
        .then(() => {
            done()
        })
        .catch(() => {
            // nothing
        })
}

// 截断文本
function truncateText(text, length) {
    if (!text) return ''
    return text.length > length ? text.substring(0, length) + '...' : text
}

// 显示完整描述
function showFullDescription(description) {
    currentDescription.value = description
    showDescriptionDialog.value = true
}

</script>

<style scoped>
.main {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: calc(100vh - 40px);
}

.header {
    margin-bottom: 20px;
}

.header h2 {
    font-size: 24px;
    font-weight: 500;
    color: #303133;
    margin: 0;
}

.search-container {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
}

.search-container .el-button {
    margin-left: 10px;
}

.data-container {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 20px;
}

.pagination-container {
    display: flex;
    justify-content: center;
    padding: 20px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.brand-dialog .el-form {
    padding: 20px;
}

.dialog-footer {
    padding: 0 20px 20px;
    text-align: right;
}

.description-cell {
    cursor: pointer;
    color: #409eff;
    text-decoration: underline;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.description-content {
    white-space: pre-wrap;
    line-height: 1.6;
    color: #606266;
}

.logo-uploader .el-upload--picture-card {
    width: 120px;
    height: 120px;
    line-height: 120px;
}

.logo-uploader .el-upload-list--picture-card .el-upload-list__item {
    width: 120px;
    height: 120px;
}

.logo-uploader-icon {
    font-size: 48px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
}

.upload-placeholder {
    position: relative;
    width: 120px;
    height: 120px;
}

.upload-text {
    position: absolute;
    bottom: 10px;
    left: 0;
    right: 0;
    text-align: center;
    color: #8c939d;
    font-size: 12px;
}

.logo-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100%;
}

.logo-circle {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    object-fit: cover;
    cursor: pointer;
}

.avatar-uploader :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 50%;
    width: 120px;
    height: 120px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
    border-color: #409eff;
}

.logo-circle-preview {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
    z-index: 1;
    position: relative;
}

.logo-placeholder {
    color: #909399;
    font-size: 12px;
}

.site-link {
    color: #409eff;
    text-decoration: none;
}

.site-link:hover {
    text-decoration: underline;
}

.preview-dialog {
    width: 600px;
}
</style>